package com.sywb.chuangyebao.contract;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;

import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.SearchInfo;
import com.sywb.chuangyebao.bean.SearchSetion;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.fragment.SearchFragment;

import org.bining.footstone.adapter.BaseRecyclerSectionAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.db.assit.QueryBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public interface SearchContract {

    interface View extends BaseRecyclerContract.View {

        FragmentManager getUserFragmentManager();

        TabLayout getTabLayout();

        ViewPager getViewPager();

        String getPushKey();

        void startSearch(String keyword);
    }

    class Presenter extends BaseRecyclerContract.Presenter<View> {

        private TabLayout tabLayout;
        private ViewPager viewpager;

        private SearchAdapter recyclerAdapter;
        private List<SearchSetion> searchSetions;

        private List<String> mTabDatas;
        private List<SearchFragment> mFragments;
        private ChannelPagerFragmentAdapter fragmentPagerAdapter;

        @Override
        public void onStart() {
            super.onStart();

            recyclerAdapter = new SearchAdapter(mActivity);
            setRecyclerAdapter(recyclerAdapter, false);

            tabLayout = mView.getTabLayout();
            viewpager = mView.getViewPager();

            String pushKey = mView.getPushKey();

            mTabDatas = Arrays.asList(mActivity.getResources().getStringArray(R.array.search_types));

            mFragments = new ArrayList<>();
            for (int i = 0; i < mTabDatas.size(); i++) {
                SearchFragment fragment = null;
                switch (i) {
                    case 0:
                        fragment = SearchFragment.newInstance("all", pushKey);
                        break;
                    case 1:
                        fragment = SearchFragment.newInstance("article", pushKey);
                        break;
                    case 2:
                        fragment = SearchFragment.newInstance("video", pushKey);
                        break;
                    case 3:
                        fragment = SearchFragment.newInstance("question", pushKey);
                        break;
                    case 4:
                        fragment = SearchFragment.newInstance("user", pushKey);
                        break;
                }
                mFragments.add(fragment);
            }
            fragmentPagerAdapter = new ChannelPagerFragmentAdapter(mView.getUserFragmentManager(), mFragments, mTabDatas);

            viewpager.setAdapter(fragmentPagerAdapter);
            viewpager.setOffscreenPageLimit(mTabDatas.size());

            tabLayout.setupWithViewPager(viewpager);
            //隐藏指示器
            tabLayout.setSelectedTabIndicatorHeight(0);

            initData();
        }

        @Override
        public void initData() {
            searchHot();
        }

        private void searchHot() {
            HttpUtils.searchHot(new HttpCallback<List<String>>() {

                @Override
                public void onSuccess(List<String> searchInfos) {
                    if (searchSetions == null) {
                        searchSetions = new ArrayList<>();
                    } else {
                        searchSetions.clear();
                    }

                    if (searchInfos != null && searchInfos.size() > 0) {
                        searchSetions.add(new SearchSetion(false, true, "热门搜索"));
                        for (int i = 0; i < searchInfos.size(); i++) {
                            SearchInfo searchInfo = new SearchInfo();
                            searchInfo.keyword = searchInfos.get(i);
                            searchSetions.add(new SearchSetion(false, i, searchInfo));
                        }
                    }

                    getSearchSetions();
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    searchSetions = null;
                    getSearchSetions();
                }
            });
        }

        public void addLoacSearch(String keyword) {
            SearchInfo searchInfo = new SearchInfo();
            searchInfo.keyword = keyword;
            searchInfo.create_time = System.currentTimeMillis();
            DbManager.getInstance().save(searchInfo);
            getSearchSetions();
        }

        private void getSearchSetions() {
            List<SearchSetion> allSearchSetions = new ArrayList<>();
            List<SearchInfo> locaSearchInfos = DbManager.getInstance().query(new QueryBuilder<SearchInfo>(SearchInfo.class).appendOrderDescBy("create_time"));
            if (locaSearchInfos != null && locaSearchInfos.size() > 0) {
                allSearchSetions.add(new SearchSetion(true, true, "搜索历史"));
                int count = locaSearchInfos.size() < 5 ? locaSearchInfos.size() : 5;
                for (int i = 0; i < count; i++) {
                    allSearchSetions.add(new SearchSetion(true, 0, locaSearchInfos.get(i)));
                }
            }

            if (searchSetions != null && searchSetions.size() > 0) {
                allSearchSetions.addAll(searchSetions);
            }

            recyclerAdapter.setDatas(allSearchSetions);
        }

        @Override
        public void onRecyclerItemClick(int postion) {
            SearchSetion searchSetion = recyclerAdapter.getItem(postion);
            if (!searchSetion.isHeader) {
                mView.startSearch(searchSetion.t.keyword);
            }
        }

        @Override
        public void onRecyclerItemChildClick(android.view.View view, int postion) {
            switch (view.getId()) {
                case R.id.iv_search_setion:
                    DbManager.getInstance().delete(SearchInfo.class);
                    getSearchSetions();
                    break;
                case R.id.iv_search_keyword:
                    SearchInfo searchInfo = recyclerAdapter.getItem(postion).t;
                    DbManager.getInstance().delete(searchInfo);
                    getSearchSetions();
                    break;
            }
        }

        public void startSearch(String keyword) {
            for (SearchFragment s : mFragments) {
                s.rxSearchDo(keyword);
            }
        }

        @Override
        public boolean useRecyclerDivider() {
            return false;
        }
    }

    class SearchAdapter extends BaseRecyclerSectionAdapter<SearchSetion> {

        public SearchAdapter(Context context) {
            super(context, R.layout.item_search_setion, R.layout.item_search_keyword, null);
        }

        @Override
        protected void setHeadData(ViewHolderHelper viewHolderHelper, int i, SearchSetion searchInfo) {
            viewHolderHelper.setText(R.id.tv_search_setion, searchInfo.header);
            if (searchInfo.isLoca) {
                viewHolderHelper.setVisibility(R.id.iv_search_setion, true);
                viewHolderHelper.setItemChildClickListener(R.id.iv_search_setion);
            } else {
                viewHolderHelper.setVisibility(R.id.iv_search_setion, false);
            }
        }

        @Override
        protected void setContentData(ViewHolderHelper viewHolderHelper, int i, SearchSetion searchInfo) {
            viewHolderHelper.setText(R.id.tv_search_keyword, searchInfo.t.keyword);
            if (searchInfo.isLoca) {
                viewHolderHelper.setVisibility(R.id.iv_search_line, true);
                viewHolderHelper.setVisibility(R.id.iv_search_keyword, true);
                viewHolderHelper.setVisibility(R.id.iv_search_index, true);
                viewHolderHelper.setVisibility(R.id.tv_search_index, false);
                viewHolderHelper.setItemChildClickListener(R.id.iv_search_keyword);
                viewHolderHelper.setImageResource(R.id.iv_search_index, R.drawable.time);
            } else {
                viewHolderHelper.setVisibility(R.id.iv_search_line, false);
                viewHolderHelper.setVisibility(R.id.iv_search_keyword, false);

                viewHolderHelper.setVisibility(R.id.iv_search_index, false);
                viewHolderHelper.setVisibility(R.id.tv_search_index, true);
                viewHolderHelper.setText(R.id.tv_search_index, String.valueOf(searchInfo.index + 1));
                viewHolderHelper.setTextColor(R.id.tv_search_index, ContextCompat.getColor(mContext, R.color.myTextBlack));
                switch (searchInfo.index) {
                    case 0:
                        viewHolderHelper.setVisibility(R.id.iv_search_index, true);
                        viewHolderHelper.setVisibility(R.id.tv_search_index, false);
                        viewHolderHelper.setImageResource(R.id.iv_search_index, R.drawable.hot);
                        break;
                    case 1:
                        viewHolderHelper.setBackgroundRes(R.id.tv_search_index, R.drawable.round8_pie_search2);
                        viewHolderHelper.setTextColor(R.id.tv_search_index, ContextCompat.getColor(mContext, R.color.colorLight));
                        break;
                    case 2:
                        viewHolderHelper.setBackgroundRes(R.id.tv_search_index, R.drawable.round8_pie_search3);
                        viewHolderHelper.setTextColor(R.id.tv_search_index, ContextCompat.getColor(mContext, R.color.colorLight));
                        break;
                    default:
                        viewHolderHelper.setBackgroundRes(R.id.tv_search_index, R.drawable.round8_pie_search);
                        break;
                }
            }
        }
    }

    class ChannelPagerFragmentAdapter extends FragmentStatePagerAdapter {

        private List<SearchFragment> fragments;
        private List<String> channels;

        public ChannelPagerFragmentAdapter(FragmentManager fragmentManager, List<SearchFragment> fragments, List<String> channels) {
            super(fragmentManager);
            this.fragments = fragments;
            this.channels = channels;
        }

        @Override
        public SearchFragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return channels == null ? "" : channels.get(position);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}

